<?php
require_once 'models/productpage.inc';
require_once 'models/TCMSStickerModel.inc';
require_once 'models/TCMSPublisher.inc';

/**
 * 
 * @author kras
 * @property TCMSCategoryModel $CategoriesModel
 * @property TCMSStickerModel $StickersModel
 */

class TMSProductSitePublisher extends TCMSPublisher {	
/**
 * @var TCMSStickerModel
 */	
	protected $_ioc_stickers_model_;
	
	protected function afterConstruct(){
		$this->_conf_classname_ = 'TMSProductPage';
		$this->_array_assumed_descendants_ = array('TMSArticlePage','TMSNomenclaturePage');
	}

	public function postProcessProperties(){
		parent::postProcessProperties();
		if (isset($this->propertyMetas['Article']))
			$this->propertyMetas['Article']->ReadOnly = true;
		if (isset($this->propertyMetas['Nomenclature']))
			$this->propertyMetas['Nomenclature']->ReadOnly = true;
		$this->propertyMetas['Sticker'] = new TOrmReferencePropertyMeta('Sticker', 'Sticker', 'TMSSticker');
		$selection = array();
		$stickers = $this->StickersModel->GetList();
		$selection = array();
		foreach ($stickers as $st)
			$selection[(string)$st->ItemId()] = (string)$st;
		$this->propertyMetas['Sticker']->SetSelection($selection);
	}

	protected function createIssue(IItem $item){
		$cn = false;
		
		if ($item->Base instanceof TMSNomenclature)
			$cn = 'TMSNomenclaturePage';
		elseif ($item->Base instanceof TMSArticle)
			$cn = 'TMSArticlePage';
		else
			throw new TCoreException(TCoreException::ERR_BAD_TYPE);
		
		return $this->CreateItem(array('Title'=>(string)$item,'IsPublished'=>false,'Product'=>$item->ItemId()),$cn);
	}
	
/**
 * @param IItem $item
 * @return IItem
 */	
	public function ItemIssue(IItem $item){
		if ($item->Base instanceof TMSNomenclature)
			$dummy = new TMSNomenclaturePage();
		elseif ($item->Base instanceof TMSArticle)
			$dummy = new TMSArticlePage();
		else 
			return parent::ItemIssue($item);
		
		$dummy->Product = $item->Base->Id;
		$dummy = $this->Adapter->Load($dummy);
		if ($dummy instanceof TMSProductPage)
			return $this->WrapObject($dummy);
		return null;	
	}
	
	protected function checkItemPage(IItem $item){
		if ($page = $this->ItemIssue($item)){
			$data = array();
			/*if (!$page->IsPublished && $item->AllowOrder)
				$data['IsPublished'] = true;
			else*/ 
			if (!$item->AllowOrder && $page->IsPublished)
				$data['IsPublished'] = false;
			
			$this->EditItem($page->ItemId(), $data);
			$this->autoAgregate($item, $page);
		}
	}
	
	
	public function OnItemChange(IItem $item){
		if ($item->Base instanceof TMSArticle){
			$this->checkItemPage($item);
			$this->checkItemPage($item->Nomenclature);
		}	
	}	
}